package fy.hr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import fy.config.FyConfig;
import fy.hr.bean.LeaveFormBean;
import fy.hr.constant.OA2HRConstant;
import fy.util.DBUtil;
import fy.util.MyUtil;


public class LeaveForm_Elimination_Dao2 {
	private static Log log = LogFactory.getLog(LeaveForm_Elimination_Dao2.class);

	private final static String UPDATE_TBM_LEAVEB = "update tbm_leaveb b set b.leavebeginday = ?, b.leavebegintime = ?, b.leaveendday = ?, b.leaveendtime = ?, b.leavesumhour = ?, b.leavenote = ? where b.pk_leave_b = ?";

	private String errorMsg;

	private LeaveFormBean leaveBean;

	private List<String> workDayArray;

	private List<String> holidayArray;

	public void setLeaveBean(LeaveFormBean leaveBean) {
		this.leaveBean = leaveBean;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public boolean write(String accountID) {
		boolean success = false;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.connect(FyConfig.getEHR_DB_CONFIG());
			System.out.println("~~~~~~~~~~"+leaveBean.getStartDate()+leaveBean.getEndDate()+leaveBean.getStartTime()+leaveBean.getEndTime()+accountID);
			pst = conn
					.prepareStatement("select p.pk_psndoc, p.pk_deptdoc, p.pk_corp, t.pk_tbm_psndoc from bd_psndoc p left join tbm_psndoc t on t.pk_psndoc=p.pk_psndoc and ( t.dr is null or t.dr = '0') where to_date(t.enddate,'yyyy-mm-dd') > sysdate and p.psnclscope='0' and p.psncode=? and ( p.dr is null or p.dr = '0')");

			pst.setString(1, leaveBean.getMemberCode());

			rs = pst.executeQuery();
			if (rs.next()) {
				String pk_psndoc = rs.getString(1);
				// String pk_deptdoc = rs.getString(2);
				String pk_corp = rs.getString(3);
				String pk_tbm_psndoc = rs.getString(4);
				DBUtil.close(rs, pst);
				
				leaveBean.setStartTime(OA2HRConstant.getWorkTime(
						leaveBean.getStartTime(), pk_corp,accountID));
				leaveBean.setEndTime(OA2HRConstant.getWorkTime(
						leaveBean.getEndTime(), pk_corp,accountID));
				System.out.println("~~~~~~~~~~"+leaveBean.getStartDate()+leaveBean.getEndDate()+leaveBean.getStartTime()+leaveBean.getEndTime());
		if (pk_tbm_psndoc != null && !"".equals(pk_tbm_psndoc)) {
			System.out.println("~~~~~~~~~~~~~~~~~~~~~1"+pk_tbm_psndoc);
					// 判断用户是否在某个时间段已经请了假
					pst = conn
							.prepareStatement("select b.leavebeginday, b.leavebegintime, b.leaveendday, b.leaveendtime, b.leavenote, b.pk_leave_b from tbm_leaveb b left join bd_psndoc p on b.psncode = p.pk_psndoc where p.psncode=? and ( b.leavebeginday = ? and b.leavebegintime = ? or b.leaveendday = ? and b.leaveendtime = ? ) and ( b.dr is null or b.dr = '0')");
					pst.setString(1, leaveBean.getMemberCode());
					pst.setString(2, leaveBean.getStartDate());
					pst.setString(3, leaveBean.getStartTime());
					pst.setString(4, leaveBean.getEndDate());
					pst.setString(5, leaveBean.getEndTime());
					rs = pst.executeQuery();
							if (rs.next()) {
						String leavebeginday = rs.getString(1);
						String leavebegintime = rs.getString(2);
						String leaveendday = rs.getString(3);
						String leaveendtime = rs.getString(4);
						leaveBean.setReason(new StringBuilder().append("(销假:")
								.append(leaveBean.getFormNumber())
								.append(")原因：").append(leaveBean.getReason())
								.append("；原请假单：").append(rs.getString(5))
								.toString());
						String pk_leave_b = rs.getString(6);

						DBUtil.close(rs, pst);

						if (setLeaveDay(leavebeginday, leavebegintime,
								leaveendday, leaveendtime)) {
							System.out.println("~~~~~~~~~~~~~~~~~~~~~2"+setLeaveDay(leavebeginday, leavebegintime,
									leaveendday, leaveendtime));
							float leaveDays = 0;
							if (!(leaveBean.getStartDate().equals(
									leaveBean.getEndDate()) && leaveBean
									.getStartTime().equals(
											leaveBean.getEndTime()))) {
								System.out.println("~~~~~~~~~~~~~~~~~~~~~3"+leaveBean.getStartDate()+leaveBean.getEndDate()+leaveBean
										.getStartTime()+leaveBean.getEndTime());
								// 查询工作日期
								pst = conn
										.prepareStatement("select calendar from tbm_psncalendar where pk_psndoc=? and calendar between ? and ? and if_rest='N' and (dr='0' or dr is null) order by calendar asc");
								pst.setString(1, pk_psndoc);
							
								pst.setString(2, leaveBean.getStartDate());
								pst.setString(3, leaveBean.getEndDate());

								rs = pst.executeQuery();

								while (rs.next()) {
									if (workDayArray == null) {
										workDayArray = new ArrayList<String>();
									}
									workDayArray.add(rs.getString(1));
								}
								DBUtil.close(rs, pst);

								// 查询节假日放假
								pst = conn
										.prepareStatement("select rq from tbm_fzqxjb where rq between ? and ? and pk_corp=? and (dr='0' or dr is null) order by rq asc");
								pst.setString(1, leaveBean.getStartDate());
								pst.setString(2, leaveBean.getEndDate());
								pst.setString(3, pk_corp);

								rs = pst.executeQuery();

								while (rs.next()) {
									if (holidayArray == null) {
										holidayArray = new ArrayList<String>();
									}
									holidayArray.add(rs.getString(1));
								}
								DBUtil.close(rs, pst);

								leaveDays = calculateLeaveDays();

								workDayArray = null;
								holidayArray = null;
							}

							pst = conn.prepareStatement(UPDATE_TBM_LEAVEB);
							// update table tbm_leaveb b set b.leavebeginday =
							// ?, b.leavebegintime = ?, b.leaveendday = ?,
							// b.leaveendtime = ?, b.leavesumhour = ?,
							// b.logoutleave_note = ? where b.pk_leave_b = ?
							pst.setString(1, leaveBean.getStartDate());
							pst.setString(2, leaveBean.getStartTime());
							pst.setString(3, leaveBean.getEndDate());
							pst.setString(4, leaveBean.getEndTime());
							pst.setString(5, String.valueOf(leaveDays));
							pst.setString(6, leaveBean.getReason());
							pst.setString(7, pk_leave_b);

							pst.execute();
							success = true;
						} else {
							this.errorMsg = "销假日期含有请假条未申请的请假日期";
						}
					} else {
						this.errorMsg = "HR系统中不存在需要销假的请假条，或者要销假时间为假期的中间段";
					}
				} else {
					this.errorMsg = "OA的请假类别无法和HR的请假类别匹配，OA请假类别为："
							+ leaveBean.getLeaveType();
				}
			} else {
				this.errorMsg = "请假人在HR系统中无考勤档案";
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("《请假条》写入失败，表单summaryId:" + leaveBean.getSummaryId()
					+ "，单据编号为：" + leaveBean.getFormNumber(), e);
			this.errorMsg = "写入HR数据库异常";
			DBUtil.rollback(conn);
		} finally {
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(rs, pst, conn);
		}
		leaveBean = null;
		if (workDayArray != null)
			workDayArray.clear();
		workDayArray = null;
		
		if (holidayArray != null)
			holidayArray.clear();
		holidayArray = null;
		return success;
	}

	private boolean setLeaveDay(String leavebeginday, String leavebegintime,
			String leaveendday, String leaveendtime) {
		boolean right = false;
		if (leavebeginday.equals(leaveBean.getStartDate())
				&& leavebegintime.equals(leaveBean.getStartTime())
				&& leaveendday.equals(leaveBean.getEndDate())
				&& leaveendtime.equals(leaveBean.getEndTime())) {
			leaveBean.setEndDate(leavebeginday);
			leaveBean.setEndTime(leavebegintime);
			right = true;
		} else if (leavebeginday.equals(leaveBean.getStartDate())
				&& leavebegintime.equals(leaveBean.getStartTime())) {
			if (MyUtil.later(leaveendday, leaveendtime, leaveBean.getEndDate(),
					leaveBean.getEndTime())) {
				if (OA2HRConstant.END_WORK_TIME[0].equals(leaveBean
						.getEndTime())) {
					leaveBean.setStartDate(leaveBean.getEndDate());
					leaveBean.setStartTime(OA2HRConstant.START_WORK_TIME[1]);
					right = true;
				} else if (OA2HRConstant.END_WORK_TIME[1].equals(leaveBean
						.getEndTime())) {
					leaveBean.setStartTime(OA2HRConstant.START_WORK_TIME[0]);
					leaveBean.setStartDate(MyUtil.tomorrow(leaveBean
							.getEndDate()));
					right = true;
				}
				leaveBean.setEndDate(leaveendday);
				leaveBean.setEndTime(leaveendtime);
			}
		} else if (leaveendday.equals(leaveBean.getEndDate())
				&& leaveendtime.equals(leaveBean.getEndTime())) {
			if (!MyUtil.later(leavebeginday, leavebegintime,
					leaveBean.getStartDate(), leaveBean.getStartTime())) {
				if (OA2HRConstant.START_WORK_TIME[1].equals(leaveBean
						.getStartTime())) {
					leaveBean.setEndDate(leaveBean.getStartDate());
					leaveBean.setEndTime(OA2HRConstant.END_WORK_TIME[0]);
					right = true;
				} else if (OA2HRConstant.START_WORK_TIME[0].equals(leaveBean
						.getStartTime())) {
					leaveBean.setEndTime(OA2HRConstant.END_WORK_TIME[1]);
					leaveBean.setEndDate(MyUtil.yesterday(leaveBean
							.getStartDate()));
					right = true;
				}
				leaveBean.setStartDate(leavebeginday);
				leaveBean.setStartTime(leavebegintime);
			}
		}
		return right;
	}

	private float calculateLeaveDays() {
		if (workDayArray == null) {
			return 0;
		} else {
			float count = 0;
			boolean isHoliday = false;
			for (int i = 0, workDayArraySize = workDayArray.size(); i < workDayArraySize; i++) {
				String workDay = workDayArray.get(i);
				isHoliday = false;
				if (holidayArray != null) {
					for (int j = 0, holidayArraySize = holidayArray.size(); j < holidayArraySize; j++) {
						String holiday = holidayArray.get(j);
						if (workDay.equals(holiday)) {
							isHoliday = true;
							break;
						}
					}
				}
				if (!isHoliday) {
					if (workDay.equals(leaveBean.getStartDate())) {
						if (workDay.equals(leaveBean.getEndDate())) {
							if (leaveBean.getStartTime().equals(
									OA2HRConstant.START_WORK_TIME[0])) {
								if (leaveBean.getEndTime().equals(
										OA2HRConstant.END_WORK_TIME[0])) {
									count = 0.5F;
								} else if (leaveBean.getEndTime().equals(
										OA2HRConstant.END_WORK_TIME[1])) {
									count = 1F;
								}
							} else if (leaveBean.getStartTime().equals(
									OA2HRConstant.START_WORK_TIME[1])) {
								if (leaveBean.getEndTime().equals(
										OA2HRConstant.END_WORK_TIME[0])) {
									count = 0;
								} else if (leaveBean.getEndTime().equals(
										OA2HRConstant.END_WORK_TIME[1])) {
									count = 0.5F;
								}
							}
						} else if (leaveBean.getStartTime().equals(
								OA2HRConstant.START_WORK_TIME[0])) {
							count = count + 1;
						} else {
							count = count + 0.5F;
						}
					} else if (workDay.equals(leaveBean.getEndDate())) {
						if (leaveBean.getEndTime().equals(
								OA2HRConstant.END_WORK_TIME[1])) {
							count = count + 1;
						} else {
							count = count + 0.5F;
						}
					} else {
						count = count + 1;
					}
				}
			}
			return count;
		}
	}
}
